//
//  PAUpdateConfigDirectionConfigVC.m
//  iCon
//
//  Created by leon on 2018/11/29.
//  Copyright © 2018年 leon. All rights reserved.
//

#import "PAUpdateConfigDirectionConfigVC.h"

#import "ChartConfig.h"
#import "PAWebSocketManager.h"
#import "PAChartConfigManager.h"
#import "PAGroupManager.h"
#import "PAAccountManager.h"

@interface PAUpdateConfigDirectionConfigVC ()

@end

@implementation PAUpdateConfigDirectionConfigVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeForm];
}
    
-(id)init
    {
        self = [super init];
        if (self) {
            self.title = @"Update Direction Config";
            //    [self initializeForm];
            self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(configData:)];
//            [self initializeForm];
        }
        return self;
    }
    
    

-(void)initializeForm{
    XLFormDescriptor * form;
    XLFormSectionDescriptor * section;
    XLFormRowDescriptor * row;
    
    form = [XLFormDescriptor formDescriptor];
    form.rowNavigationOptions = XLFormRowNavigationOptionNone;
    //    form.assignFirstResponderOnShow = YES;
    section = [XLFormSectionDescriptor formSectionWithTitle:nil];
    //
        XLFormRowDescriptor *infoRowDescriptor = [XLFormRowDescriptor formRowDescriptorWithTag:@"chartName"rowType:XLFormRowDescriptorTypeInfo];
        infoRowDescriptor.title = @"chartName";
        infoRowDescriptor.value = self.chartConfig.chartName;
        [section addFormRow:infoRowDescriptor];
    // Name
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"title" rowType:XLFormRowDescriptorTypeText title:@"title"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value =self.chartConfig.config[CONFIG_KEY_TITLE];
    //    row.required = YES;
    [section addFormRow:row];
    
    // DateTime
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"startTime" rowType:XLFormRowDescriptorTypeDate title:@"startTime"];
    row.required = YES;
    NSString *start = self.chartConfig.config[CONFIG_KEY_RANGECONFIG][@"startTime"];
    if(![start isKindOfClass:[NSNull class]] ){
         NSDate *time = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval) ([start doubleValue] / 1000)];
        //    NSString *time = self.chartConfig.config[CONFIG_KEY_RANGECONFIG][@"startTime"];
        row.value = time;
    }

//    [row.cellConfigAtConfigure setObject:[NSDate new] forKey:@"maximumDate"];
//     [row.cellConfigAtConfigure setObject:[NSDate dateWithTimeIntervalSinceNow:(-60*60*24*366)] forKey:@"maximumDate"];
    [section addFormRow:row];
    
    // DateTime
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"endTime" rowType:XLFormRowDescriptorTypeDate title:@"endTime"];
    NSString *end = self.chartConfig.config[CONFIG_KEY_RANGECONFIG][@"endTime"];
    if(end!=nil && ![end isKindOfClass:[NSNull class]] &&![end isEqualToString:@""]){
        NSDate *time2 = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval) ([end doubleValue] / 1000)];
        row.value =time2;
    }
//     [row.cellConfigAtConfigure setObject:[NSDate new] forKey:@"maximumDate"];
//      [row.cellConfigAtConfigure setObject:[NSDate dateWithTimeIntervalSinceNow:(-60*60*24*366)] forKey:@"maximumDate"];
    [section addFormRow:row];
    
    // MaxRecords
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"maxRecords" rowType:XLFormRowDescriptorTypeNumber title:@"maxRecords"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value = self.chartConfig.config[CONFIG_KEY_RANGECONFIG][@"maxRecords"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"maxHistoricalPoints" rowType:XLFormRowDescriptorTypeNumber title:@"maxHistoricalPoints"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value = self.chartConfig.config[@"maxHistoricalPoints"];
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"orderby" rowType:XLFormRowDescriptorTypeSelectorPush title:@"Orderby"];
    row.selectorOptions = @[@"DESC",@"ASC"];
    row.value = self.chartConfig.config[CONFIG_KEY_RANGECONFIG][@"orderby"];
    
    [section addFormRow:row];
    

    // Name
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"directionname" rowType:XLFormRowDescriptorTypeText title:@"directionname"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value = self.chartConfig.config[CONFIG_KEY_PARAMS][@"directionname"];
    row.required = YES;
    [section addFormRow:row];
    
//    // Name
//    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"quarter" rowType:XLFormRowDescriptorTypeText title:@"quarter"];
//    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
//    row.value = self.chartConfig.config[CONFIG_KEY_PARAMS][@"quarter"];
//    //    row.required = YES;
//    [section addFormRow:row];
//    
//    
//    // Name
//    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"ctd" rowType:XLFormRowDescriptorTypeText title:@"ctd"];
//    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
//    row.value = self.chartConfig.config[CONFIG_KEY_PARAMS][@"ctd"];
//    //    row.required = YES;
//    [section addFormRow:row];
    
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"quarter" rowType:XLFormRowDescriptorTypeMultipleSelectorPopover title:@"quarter"];
    NSDictionary *metadata = [PAAppContext sharedInstance].metaData;
    NSString *quarterStr = metadata[@"Quarter"];
    if(quarterStr!=nil && ![quarterStr isEqualToString:@""]){
        row.selectorOptions = [quarterStr componentsSeparatedByString:@","];
        row.value =[quarterStr componentsSeparatedByString:@","];
    }else{
        row.selectorOptions =@[];
    }
    [section addFormRow:row];
    
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"ctd" rowType:XLFormRowDescriptorTypeMultipleSelectorPopover title:@"ctd"];
    
    NSString *ctdStr = metadata[@"CTD"];
    if(ctdStr!=nil && ![ctdStr isEqualToString:@""]){
        row.selectorOptions = [ctdStr componentsSeparatedByString:@","];
        row.value =[ctdStr componentsSeparatedByString:@","];
    }else{
        row.selectorOptions =@[];
    }
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"business.hours" rowType:XLFormRowDescriptorTypeMultipleSelectorPopover title:@"businesshours"];
    row.selectorOptions = @[@"6:30-23:00",
                            @"8:00-18:00",
                            @"7:00-11:45,13:30-18:00",
                            @"7:30-11:30,13:00-15:16",
                            @"8:00-12:00,13:00-18:00",
                            @"9:00-11:45,13:00-15:33",
                            @"9:00-12:00,13:00-17:00",
                            @"9:00-12:00,13:00-17:30",
                            @"9:14-11:30,13:00-15:15"];
    
    if(self.chartConfig.config[CONFIG_KEY_PARAMS][@"business.hours"]!=nil){
        row.value = @[self.chartConfig.config[CONFIG_KEY_PARAMS][@"business.hours"]];
    }else{
        row.value = @[@"8:00-12:00,13:00-18:00"];
    }
    [section addFormRow:row];
    [form addFormSection:section];
    
    section = [XLFormSectionDescriptor formSectionWithTitle:nil];
    XLFormRowDescriptor * buttonRow = [XLFormRowDescriptor formRowDescriptorWithTag:@"save" rowType:XLFormRowDescriptorTypeButton title:@"Save"];
    buttonRow.action.formSelector = @selector(configData:);
    [section addFormRow:buttonRow];
    
    [form addFormSection:section];
    
    self.form = form;
}
    
    
    
-(void)configData:(XLFormRowDescriptor *)sender
    {
        if (![self validateDatas]) {
            return;
        }
        
        XLFormRowDescriptor * row = [self.form formRowWithTag:@"chartName"];
        
        NSDictionary *dic = [self formValues];
        NSMutableDictionary *mdic = [dic mutableCopy];
        NSArray *hours =dic[@"business.hours"];
        mdic[@"business.hours"] = [hours componentsJoinedByString: @","];
        if ([dic[@"chart.ownaxis"] isKindOfClass:[NSNull class]] || [dic[@"chart.ownaxis"] isEqual:@0]) {
            mdic[@"chart.ownaxis"] = @NO;
        }else{            mdic[@"chart.ownaxis"] = @YES;
            
        }
        if ([dic[@"window.frameless"] isKindOfClass:[NSNull class]] || [dic[@"window.frameless"] isEqual:@0]) {
            mdic[@"window.frameless"] = @NO;
        }else{
            mdic[@"window.frameless"] = @YES;
            
        }
        
        if (dic[@"startTime"]!=nil && ![dic[@"startTime"] isKindOfClass:[NSNull class]]) {
            //mdic[@"startTime"] = [dic[@"startTime"] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
            long t =  [dic[@"startTime"] timeIntervalSince1970];
            mdic[@"startTime"] = [NSNumber numberWithLong:t*1000];
        }else{
            //        mdic[@"startTime"] = [[NSDate new] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
            long t =  [[NSDate new] timeIntervalSince1970];
            mdic[@"startTime"] = [NSNumber numberWithLong:t*1000];
        }
        if (dic[@"endTime"]!=nil && ![dic[@"endTime"] isKindOfClass:[NSNull class]]) {
            
            long t =  [dic[@"endTime"] timeIntervalSince1970];
            mdic[@"endTime"] = [NSNumber numberWithLong:t*1000];
            //      mdic[@"endTime"] = [dic[@"endTime"] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
        }else{
            mdic[@"endTime"] = @"";
        }
        if(mdic[@"quarter"] == nil || [mdic[@"quarter"] isKindOfClass:[NSNull class]]){
            [mdic removeObjectForKey:@"quarter"];
        }else{
            mdic[@"quarter"]  = [dic[@"quarter"] componentsJoinedByString:@","];
        }
        if(mdic[@"ctd"] == nil || [mdic[@"ctd"] isKindOfClass:[NSNull class]]){
            [mdic removeObjectForKey:@"ctd"];
        }else{
            mdic[@"ctd"]  = [dic[@"ctd"] componentsJoinedByString:@","];
        }
        
        NSLog(@"%@",mdic);
        if(row.value == nil || [row.value isKindOfClass: [NSNull class]] || [row.value isEqualToString: @""]){
            row.value = dic[@"directionname"];
        }
        mdic[@"directionname"] = [dic[@"directionname"] lowercaseString];
       
        if(![mdic[@"endTime"] isEqualToString:@""]){
            long long t = [mdic[@"endTime"] longLongValue] - 7776000L*1000L;
            t = MAX([mdic[@"startTime"] longLongValue],t);
            mdic[@"startTime"] = [NSNumber numberWithLongLong: t];
        }else{
            long long t =  ([[NSDate new] timeIntervalSince1970] - 7776000L)*1000L;
             t = MAX([mdic[@"startTime"] longLongValue],t);
            mdic[@"startTime"] = [NSNumber numberWithLongLong: t];
        }
        
        ChartConfig *chartConfig = [ChartConfig new];
        NSMutableDictionary *mConfig = [NSMutableDictionary new];
        
        mConfig[CONFIG_KEY_CONFIGSOURCE] = w_cofingSource;
        mConfig[CONFIG_KEY_HOST] = [PAAppContext sharedInstance].w_host;
        mConfig[CONFIG_KEY_PORT] = [NSNumber numberWithLong:[PAAppContext sharedInstance].w_port];
        mConfig[CONFIG_KEY_TYPE] = @"command";
        mConfig[CONFIG_KEY_COMMAND] = @"config";
        mConfig[CONFIG_KEY_CHARTNAME] =  row.value;
        mConfig[CONFIG_KEY_TITLE] = mdic[CONFIG_KEY_TITLE];
        mConfig[CONFIG_KEY_GRAPHTYPE] = w_graphType;
        mConfig[CONFIG_KEY_APPID] =[PAAppContext sharedInstance].appid;
        chartConfig.chartName = row.value;
        chartConfig.config = mConfig;
        mConfig[CONFIG_KEY_RANGECONFIG] =  @{@"columnNames":@[@"dummy"], @"rowNames":@[@"dummy"], @"rangeName": @"dummy",@"orderby":dic[@"orderby"],@"maxRecords":dic[@"maxRecords"],@"startTime":mdic[@"startTime"],@"endTime":mdic[@"endTime"]};
        
        mdic[@"mergestrategy"] = @"INTERSECT";
        mdic[@"ohlc.chartType"] = @"OHLC";
        mdic[@"ohlc.grouping.relaxed"] = @YES;
        mdic[@"ohlc.period"] = @"1h";
        mdic[@"ohlc.start"] = @"-5d";
        [mdic removeObjectForKey:@"startTime"];
        [mdic removeObjectForKey:@"endTime"];
        [mdic removeObjectForKey:@"orderby"];
        [mdic removeObjectForKey:@"maxRecords"];
        [mdic removeObjectForKey:@"chartName"];
        
        mConfig[@"parameters"] = mdic;
        //如果本地已经有该config了，则提醒用户
        if ([[PAAppContext sharedInstance].chartNames containsObject:row.value]) {
            
          [self processChartConfig:chartConfig isAdd:NO];
            
        }else{
            
            
        [self processChartConfig:chartConfig isAdd:YES];
            
        }
        
    }
    
- (void)processChartConfig:(ChartConfig *)chartConfig isAdd:(BOOL) isAdd
    {
        //1.发送config
//        if(![[PAWebSocketManager sharedInstance] sendMsg:chartConfig.config.mj_JSONString]) return;
        
        //2.保存到currentChart
        BOOL isUpdate = [PAChartConfigManager saveChartConfig:chartConfig];
        
        //3.查看是否选中群组，如果选中，则添加到群组中
        NSString *groupName = [PAAccountManager loadCurrentGroupName];
        if (groupName!=nil &&![groupName isEqualToString:@""]) {
            
            [PAGroupManager addChartConfig:chartConfig.chartName toGroup:groupName];
        }else{
            [PAGroupManager updateGroup:@"Default"  withChartNames:@[chartConfig.chartName]];
        }
        //4.新增或者修改chartConfigs
        if (isAdd) {
            [[PAAppContext sharedInstance].chartConfigs addObject:chartConfig];
        }else{
            NSInteger index = [[PAAppContext sharedInstance].chartNames indexOfObject:chartConfig.chartName];
            [[PAAppContext sharedInstance].chartConfigs replaceObjectAtIndex:index withObject:chartConfig];
        }
        //5.通知collectionview 添加graph
        if (isUpdate) {
            [[NSNotificationCenter defaultCenter] postNotificationName:PACurrentChartUpdateNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
            //LQUpdateConfigNotification
           
        }else{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:PAChartListVCItemClickNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
        }
        
        
      //6.
        [self dismissViewControllerAnimated:YES completion:^{
              [[NSNotificationCenter defaultCenter] postNotificationName:LQUpdateConfigNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
        }];
    }
    
-(BOOL)validateDatas{
    NSArray * array = [self formValidationErrors];
    if (array ==nil || array.count<1) {
        return YES;
    }else{
        [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            XLFormValidationStatus * validationStatus = [[obj userInfo] objectForKey:XLValidationStatusErrorKey];
            UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:[self.form indexPathOfFormRow:validationStatus.rowDescriptor]];
            [cell shake];
            
        }];
        return NO;
    }
    
    
    
}

@end
